<!--
/**
@template: 见证工作加班统计
@author: ChaoPengWang(wangcp-a@glodon.com)
@update: 2022/4/16 9:36 PM
-->
<template>
  <div class="layout-wrapper layout-witness">
    <div class="layout-header layout-search">
      <el-form :inline="true"
               :model="searchForm"
               ref="form"
               style="display:flex; flex-wrap: wrap; padding-right:10px">
        <el-form-item style="flex: 1; ">
          <el-button type="primary" @click="download">导出{{ isDownloading ? "中..." : "" }}</el-button>
          <el-button type="primary" @click="print" flex="1">打印</el-button>
        </el-form-item>

        <el-form-item label="见证人员" prop="witnessUserName">
          <el-select
            v-model="searchForm.witnessUserName"
            class="ui-w200"
            option-max-width="300px"
            placeholder="请选择"
            multiple
            clearable
          >
            <el-option
              v-for="item in witnessUserNameOption"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="见证日期" prop="witnessTime">
          <el-date-picker
            v-model="searchForm.witnessTime"
            class="ui-w260"
            unlink-panels
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"

          />

        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getData">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div ref="demo" style="display:none;"></div>
    <div class="statistics">
      <div class="statistics-title">
        <div >
          见证工作加班时长统计
        </div>
      </div>
      <div class="statistics-table">
        <div class="statistics-table-tr statistics-table-title">
          <div>序号</div>
          <div>见证人员</div>
          <div>加班日期</div>
          <div>加班事由</div>
          <div>加班开始时间</div>
          <div>加班结束时间</div>
          <div>加班时长（小时）</div>
          <div>备注</div>
        </div>
        <template v-for="(item, index) in extraList">
          <div :key="item.witnessSubTaskIds + index" class="statistics-table-tr statistics-table-data">
            <div>{{ index+1 }}</div>
            <div>{{ item.witnessUserName }}</div>
            <div>{{ item.overtimeDate }}</div>
            <div>{{ item.overtimeReason }}</div>
            <div>{{ item.overtimeStartTime }}</div>
            <div>{{ item.overtimeEndTime }}</div>
            <div>{{ item.overtimeDuration }}</div>
            <div>{{ item.remark }}</div>
          </div>
        </template>
      </div>
    </div>
    <div class="statistics" ref="statisticsTable" style="display:none;">
      <div class="statistics-title">
        <div >
          见证工作加班时长统计
        </div>
      </div>
      <div class="statistics-table">
        <div class="statistics-table-tr statistics-table-title">
          <div>序号</div>
          <div>见证人员</div>
          <div>加班日期</div>
          <div>加班事由</div>
          <div>加班开始时间</div>
          <div>加班结束时间</div>
          <div>加班时长（小时）</div>
          <div>备注</div>
        </div>
        <template v-for="(item, index) in extraListPrint">
          <div :key="item.witnessSubTaskIds + index" class="statistics-table-tr statistics-table-data">
            <div>{{ index+1 }}</div>
            <div>{{ item.witnessUserName }}</div>
            <div>{{ item.overtimeDate }}</div>
            <div>{{ item.overtimeReason }}</div>
            <div>{{ item.overtimeStartTime }}</div>
            <div>{{ item.overtimeEndTime }}</div>
            <div>{{ item.overtimeDuration }}</div>
            <div>{{ item.remark }}</div>
          </div>
        </template>
      </div>
    </div>

    <div class="layout-footer">
      <pagination
        v-if="pageObj.total > pageObj.pageSizes[0]"
        :total="pageObj.total"
        :page.sync="pageObj.currentPage"
        :limit.sync="pageObj.pageSize"
        :page-sizes="pageObj.pageSizes"
      />
    </div>
  </div>
</template>
<script>
import moment from "moment";
import axios from "axios";
const date = moment().subtract(1, "day").format("YYYY-MM-DD");// 见证开始时间
import css from './extraCss.js'
import { GZAPI_EvaluationTime } from "../../../../gz_plugin/api";
import { OnCalendar } from "@/api/api";

export default {
  name:'extraStatistics',
  components: { },
  computed: {
  },
  props: {},
  data() {
    return {
      witnessUserNameOption: [], // 见证人员选项
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ],
        // disabledDate(time){
        //   return time > new Date(date)
        // }
      },
      isDownloading: false,
      searchForm: {
        witnessTime: [],
        witnessUserName:[]
      },
      tableLoading: false,
      extraList: [], // 加班统计数据
      extraListPrint:[],
      pageObj: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
    };
  },
  created() {
    this.getWitnessUserName();
  },
  watch: {
    searchForm: {
      deep: true,
      immediate: true,
      handler() {
        // 获取数据
        this.getData();
      }
    },
    "pageObj.currentPage"() {
      this.getData();
    },
    "pageObj.pageSize"() {
      this.getData();
    }
  },
  methods: {
    // 获取见证人员
    async getWitnessUserName() {
      try {
        const { searchForm: { witnessTime } } = this;
        const { code, data, message } = await OnCalendar({
          endDate: "2022-10-01 00:00:00",
          startDate: "2022-09-01 00:00:00"
        });
        if (code === 0) {

          this.witnessUserNameOption = data.map(({ userName }) => ({
            label:userName,
            value:userName
          }));
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        console.error(e);
      }
    },

    // 重置
    reset() {
      this.searchForm = {
        witnessTime: [],
        witnessUserName:[]
      };
    },

    // 获取表格数据
    async getData() {
      try {

        const { searchForm: { witnessTime, witnessUserName }, pageObj: { currentPage, pageSize }} = this;
        const params = {
          witnessUserNameList:witnessUserName,
          currentPage,
          pageSize,
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        }
        this.tableLoading = true;
        const { code, data, message } =  await GZAPI_EvaluationTime.overtimeStatistics(params);
        if (code === 0) {
          this.extraList = data.data;
          this.pageObj.total = data.pageBean.count;
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.tableLoading = false;
      }
    },

    async getPrintData() {
      try {
        const pageSize = this.pageObj.total
        const { searchForm: { witnessTime, witnessUserName }, pageObj: { currentPage }} = this;
        const params = {
          witnessUserNameList:witnessUserName,
          currentPage: 1,
          pageSize,
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        }
        const { code, data, message } =  await GZAPI_EvaluationTime.overtimeStatistics(params);
        if (code === 0) {
          this.extraListPrint = data.data;
        } else {
          this.$message.warning(message);
        }
      } catch (e) {
        console.error(e);
      }
    },

    async download() {
      try {
        if (this.isDownloading) {
          return;
        }
        const {
          searchForm: { witnessUserName, witnessTime },
          pageObj: { currentPage, pageSize }
        } = this;

        const params = {
          currentPage,
          pageSize,
          witnessUserNameList:witnessUserName
        };
        if (witnessTime && witnessTime.length === 2) {
          params.startTime = `${witnessTime[0]} 00:00:00`;
          params.endTime = `${witnessTime[1]} 23:59:59`;
        }

        const instance = axios.create({
          contentType: "application/json;charset=UTF-8",
          responseType: "blob"
        });

        const res = await instance.post("/gdw/gz/witness/export/overtimeStatistics", params);
        const fileName = "见证工作加班时长统计.xlsx";
        const csvData = new Blob([res.data], { type: "application/xlsx" });
        // try{
        //   const data = await blobByUtf8(csvData);
        //   if(data && data.message){
        //     this.$message.warning(data.message)
        //     return;
        //   }
        // } catch (e) {
        //
        // }

        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(csvData, fileName);
        } else {
          const a = document.createElement("a");
          document.body.appendChild(a);
          a.style = "display: none";
          const url = window.URL.createObjectURL(csvData);
          a.href = url;
          a.download = fileName;
          a.click();
          a.remove();
          window.URL.revokeObjectURL(url);
        }

        let id = setTimeout(() => {
          clearTimeout(id);
          this.$message.success("导出成功");
        }, 100);
      } catch (e) {
        console.error(e);
      } finally {
        this.isDownloading = false;
      }
    },

    async print() {
      await this.getPrintData()
      let iframe = document.getElementById("iframeId");
      if (iframe) {
        this.$refs.demo.removeChild(iframe);
      }
      iframe = document.createElement("iframe");
      iframe.id = "iframeId";
      const style = document.createElement('style');
      style.innerText = css;


      iframe.onload = () => {
        const iframeBody = iframe.contentDocument || iframe.contentWindow.document;
        iframeBody.body.innerHTML = this.$refs.statisticsTable.innerHTML;
        iframeBody.body.appendChild(style);
        iframe.contentWindow.print();
      }

      this.$refs.demo.appendChild(iframe);

    },
  }
};
</script>
<style lang="scss" scoped>
.statistics{
  padding: 10px;
  box-sizing: border-box;
}

.statistics-title > div{
  font-size: 18px;
  line-height: 20px;
  font-weight: bolder;
  text-align: center;
  margin-bottom: 20px
}

.statistics-table{
  width: 100%;
  border-top: 1px solid #d2d2d2;
  border-left: 1px solid #d2d2d2;
  font-size: 14px;
  text-align: center;
  box-sizing: border-box;
}

.statistics-table > div{
  display: flex;
  width: 100%;
}
.statistics-table > div > div{
  padding: 8px 10px;
  border-bottom: 1px solid #d2d2d2;
  border-right: 1px solid #d2d2d2;
  line-height: 23px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.statistics-table-tr>div:nth-child(1) {
  width: 5%;
}
.statistics-table-tr>div:nth-child(2) {
  width: 10%;
}

.statistics-table-tr>div:nth-child(3) {
  width: 10%;
}
.statistics-table-tr>div:nth-child(4) {
  width: 25%;
}
.statistics-table-tr>div:nth-child(5) {
  width: 15%;
}
.statistics-table-tr>div:nth-child(6) {
  width: 15%;
}
.statistics-table-tr>div:nth-child(7) {
  width: 10%;
}
.statistics-table-tr>div:nth-child(8) {
  width: 10%;
}



.statistics-table-title{
  font-weight: 700;
  background-color: #e5e5e5;
}

</style>
